// stores/resumeStore.js
import { defineStore } from 'pinia';
import instance from '@/utils/request';

export const useResumeStore = defineStore('resume', {
  state: () => ({
    allTemplates: [], // 从后端获取的所有模板
    selectedTemplateId: 1, // 默认选择第一个模板（ID为数字）
    currentTemplate: null,
    currentResumeId: null, // 当前编辑的简历ID，用于更新
    currentResumeName: '', // 当前简历名称，用于下载PDF
    
    form: {
      name: '',
      gender: '',
      phone: '',
      email: '',
      intention: '',
      intro: '',
      photoUrl: ''
    },
    
    educationList: [{ school: '', major: '', startDate: '', endDate: '' }],
    workList: [{ company: '', position: '', startDate: '', endDate: '', desc: '' }],
    skillsList: ''
  }),
  
  getters: {
    // 用于调试
    getPhotoUrl() {
      console.log('获取照片URL:', this.form.photoUrl);
      return this.form.photoUrl;
    },
    getSkills() {
      console.log('获取技能列表:', this.skillsList);
      return this.skillsList;
    }
  },
  
  actions: {
    // 从后端加载所有模板
    async fetchTemplates() {
      try {
        console.log('📥 从后端加载模板...');
        const response = await instance.request({
          method: 'GET',
          url: '/templates'
        });
        
        if (response.code === 0) {
          // 将后端的 template_data 字段解析为模板对象
          this.allTemplates = response.data.map(item => {
            const template = item.template_data;
            // 确保模板有modules配置，如果没有则添加默认的
            if (!template.modules) {
              template.modules = ['photo', 'basic', 'education', 'work', 'skills'];
            }
            return template;
          });
          console.log('✅ 模板加载成功，数量:', this.allTemplates.length);
          
          // 设置默认模板
          if (this.allTemplates.length > 0) {
            this.currentTemplate = this.allTemplates[0];
            this.selectedTemplateId = this.allTemplates[0].id;
          }
        } else {
          console.error('❌ 加载模板失败:', response.msg);
        }
      } catch (error) {
        console.error('❌ 加载模板出错:', error);
      }
    },
    
    loadTemplate(templateId) {
      console.log('切换模板：', templateId);
      const targetTemplate = this.allTemplates.find(t => t.id === templateId);
      if (targetTemplate) {
        // 确保模板有modules配置
        if (!targetTemplate.modules) {
          targetTemplate.modules = ['photo', 'basic', 'education', 'work', 'skills'];
        }
        this.currentTemplate = targetTemplate;
        this.selectedTemplateId = templateId;
        this.form.photoUrl = '';
        console.log('模板样式生效：', this.currentTemplate.style.base.primaryColor);
      } else {
        console.error('模板不存在：', templateId);
      }
    },
    
    addEducation() {
      this.educationList.push({ school: '', major: '', startDate: '', endDate: '' });
    },
    
    removeEducation(index) {
      if (this.educationList.length > 1) {
        this.educationList.splice(index, 1);
      }
    },
    
    addWork() {
      this.workList.push({ company: '', position: '', startDate: '', endDate: '', desc: '' });
    },
    
    removeWork(index) {
      if (this.workList.length > 1) {
        this.workList.splice(index, 1);
      }
    },

    // 从后端加载简历数据
    async loadResumeData(resumeId) {
      try {
        console.log('📥 加载简历数据，ID:', resumeId);
        const response = await instance.request({
          method: 'GET',
          url: `/resumes/${resumeId}`
        });
        
        if (response.code === 0) {
          const resume = response.data;
          console.log('✅ 简历数据加载成功:', resume);
          console.log('基本信息:', resume.basic_info);
          console.log('教育经历:', resume.education_list);
          console.log('工作经历:', resume.work_list);
          
          // 填充数据到 store
          this.currentResumeId = resume.id;
          this.currentResumeName = resume.resume_name;
          this.selectedTemplateId = resume.template_id;
          
          // 填充基本信息
          this.form.name = resume.basic_info?.name || '';
          this.form.gender = resume.basic_info?.gender || '';
          this.form.phone = resume.basic_info?.phone || '';
          this.form.email = resume.basic_info?.email || '';
          this.form.intention = resume.basic_info?.intention || '';
          this.form.intro = resume.basic_info?.intro || '';
          this.form.photoUrl = resume.photo_url || '';
          
          console.log('填充后的表单数据:', this.form);
          
          // 填充教育经历（处理日期格式）
          if (resume.education_list && resume.education_list.length > 0) {
            this.educationList = resume.education_list.map(edu => ({
              school: edu.school || '',
              major: edu.major || '',
              startDate: edu.startDate || '',
              endDate: edu.endDate || ''
            }));
          } else {
            this.educationList = [{ school: '', major: '', startDate: '', endDate: '' }];
          }
          
          console.log('填充后的教育经历:', this.educationList);
          
          // 填充工作经历（处理日期格式）
          if (resume.work_list && resume.work_list.length > 0) {
            this.workList = resume.work_list.map(work => ({
              company: work.company || '',
              position: work.position || '',
              startDate: work.startDate || '',
              endDate: work.endDate || '',
              desc: work.desc || ''
            }));
          } else {
            this.workList = [{ company: '', position: '', startDate: '', endDate: '', desc: '' }];
          }
          
          console.log('填充后的工作经历:', this.workList);
          
          // 填充技能列表
          this.skillsList = resume.skills_list || '';
          console.log('填充后的技能列表:', this.skillsList);
          
          // 加载对应的模板
          if (this.allTemplates.length > 0) {
            this.loadTemplate(resume.template_id);
            console.log('已切换模板:', resume.template_id);
          }
          
          return true;
        } else {
          console.error('❌ 加载简历失败:', response.data.msg);
          return false;
        }
      } catch (error) {
        console.error('❌ 加载简历出错:', error);
        return false;
      }
    },

    // 清空简历数据（用于新建）
    clearResumeData() {
      this.currentResumeId = null;
      this.currentResumeName = '';
      
      this.form = {
        name: '',
        gender: '',
        phone: '',
        email: '',
        intention: '',
        intro: '',
        photoUrl: ''
      };
      
      this.educationList = [{ school: '', major: '', startDate: '', endDate: '' }];
      this.workList = [{ company: '', position: '', startDate: '', endDate: '', desc: '' }];
      this.skillsList = '';
    }
  }
});